//主视图 搜索界面

import { join } from 'path'
import { BrowserView, BrowserWindow, shell, session } from 'electron'
import * as utils from '../utils'

// async function execCommand(cmd: string, modules: string[]) {
//   return new Promise((resolve, reject) => {
//     const module = cmd !== 'remove' && cmd !== 'link' ? modules.map((m) => `${m}@latest`) : modules
//     let param = [cmd]
//     if (cmd === 'link') {
//       param = param.concat('--global')
//     }
//     param = param.concat(...module)

//     console.log(param)

//     const cwd = join(process.cwd(), 'test')
//     if (!fs.existsSync(cwd)) {
//       fs.mkdirSync(cwd)
//       fs.writeFileSync(join(cwd, 'package.json'), '{}')
//     }

//     const npm = spawn('pnpm', param, { cwd })

//     const output = {
//       stdout: '',
//       stderr: ''
//     }

//     npm.stdout.on('data', (data: string) => {
//       output.stdout += data // 获取输出日志
//     })

//     npm.stderr.on('data', (data: string) => {
//       output.stderr += data // 获取报错日志
//     })

//     npm.on('close', (code: number) => {
//       if (!code) {
//         resolve({ code: 0, data: output }) // 如果没有报错就输出正常日志
//       } else {
//         reject({ code: code, data: output }) // 如果报错就输出报错日志
//       }
//     })
//   })
// }

const searchBarHeight = 56
const searchBarWidth = 800

class MainWindow {
  private _win?: BrowserWindow

  private _view?: BrowserView

  readyToShow?: boolean

  get win() {
    return this.createWindow()
  }

  toggle() {
    if (this.win.isVisible()) {
      this.win.hide()
    } else {
      this.show()
    }
  }

  hide() {
    this.win.hide()
  }

  show() {
    if (this.readyToShow) {
      this.win.showInactive()
      this.win.focus()
    } else {
      console.log('not ready to show...')
    }
  }

  openPlugin(elem: plugin.PluginElem, plugins: plugin.Plugin[]) {
    if (this._view) {
      this.win.setBrowserView(this._view)
      const defaultPluginHeight = 600
      this._view.setBounds({
        x: 0,
        y: searchBarHeight,
        width: searchBarWidth,
        height: defaultPluginHeight
      })
      this.setExpandHeight(defaultPluginHeight)
      this._view.webContents.focus()
      return

      // this.win.removeBrowserView(this._view) //TODO 需要验证是否移除了view
      // this._view = undefined
    }

    const plugin = utils.findPlugin(plugins, elem)
    if (!plugin) {
      console.log('未找到插件，已删除')
      return
    }

    const config = plugin.config
    //判断是否是ui模式
    if (config.main) {
      //UI模式
      const s = session.fromPartition(`<${plugin.name}>`)
      s.setPreloads([join(__dirname, '../preload/index.js')])

      const preload = config.preload ? join(plugin.baseDir, config.preload) : undefined

      const view = new BrowserView({
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: false,
          session: s,
          sandbox: false,
          devTools: true,
          webSecurity: false,
          defaultEncoding: 'utf-8',
          preload
        }
      })

      // view.webContents.openDevTools()

      view.webContents.on('before-input-event', (_, input) => {
        if (input.type === 'keyDown' && input.key === 'Escape') {
          this.win.webContents.executeJavaScript(`window.stools?.hooks?.onExitPlugin()`)
          this.win.webContents.focus()
        }
      })

      // eslint-disable-next-line @typescript-eslint/no-var-requires
      require('@electron/remote/main').enable(view.webContents)

      view.webContents.loadURL(config.main)

      this.win.setBrowserView(view)

      const defaultPluginHeight = 600
      view.setBounds({
        x: 0,
        y: searchBarHeight,
        width: searchBarWidth,
        height: defaultPluginHeight
      })
      this.setExpandHeight(defaultPluginHeight)

      view.webContents.on('destroyed', () => {
        console.log('destroyed')
      })

      view.webContents.once('did-finish-load', () => {
        view.webContents.focus()
      })

      this._view = view
    } else {
      //模板 TODO
      //list/cmd
    }
  }

  exitPlugin() {
    if (this._view) {
      this.win.removeBrowserView(this._view)
      //销毁webcontent
      // this._view.webContents.close()
      // this._view = undefined
    }
  }

  setExpandHeight(height: number) {
    this.win.setSize(searchBarWidth, searchBarHeight + height)
  }

  createWindow() {
    if (this._win) {
      return this._win
    }

    const win = new BrowserWindow({
      width: searchBarWidth,
      height: searchBarHeight, //搜索框高度
      resizable: false,
      useContentSize: true,
      type: 'panel',
      opacity: 0.92,
      hiddenInMissionControl: true,
      autoHideMenuBar: true,
      skipTaskbar: true,
      alwaysOnTop: true,
      acceptFirstMouse: true,
      show: false,
      frame: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        sandbox: false,
        defaultEncoding: 'utf-8',
        spellcheck: false,
        preload: join(__dirname, '../preload/index.js')
      }
    })

    // eslint-disable-next-line @typescript-eslint/no-var-requires
    require('@electron/remote/main').enable(win.webContents)

    //点击跳转浏览器
    win.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    win.once('ready-to-show', () => {
      this.readyToShow = true
    })

    // win.on('blur', () => {
    //   win.hide()
    // })

    win.on('show', () => {
      win.webContents.executeJavaScript(`window.stools?.hooks?.onShow()`)
    })

    win.on('hide', () => {
      win.webContents.executeJavaScript(`window.stools?.hooks?.onHide()`)
    })

    win.on('resize', () => {
      const size = this.win.getSize()
      this._view?.setBounds({
        x: 0,
        y: searchBarHeight,
        width: size[0],
        height: size[1] - searchBarHeight
      })
    })

    this._win = win
    return win
  }
}

export const mainWin = new MainWindow()
